package com.wm.task.util;

import com.wm.task.Test;
import com.wm.task.vo.User;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DbHelper {
    private static String url ;//= "jdbc:mysql://localhost:3306/moviesys?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
    private static String user ;//= "root";
    private static String pass ;//= "123456";
    private static Driver driver;

    static {
        initProperties();
        try {
            driver = new com.mysql.cj.jdbc.Driver();
            DriverManager.registerDriver(driver);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
    private static void initProperties() {
        try {
            Properties properties = new Properties();
            properties.load(Test.class.getClassLoader().getResourceAsStream("db.properties"));
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pass = properties.getProperty("pass");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void update(String sql, Object... params) {
        try (
                Connection connection = DriverManager.getConnection(url, user, pass);
                PreparedStatement ps = connection.prepareStatement(sql);
        ) {
            for (int i = 0; params != null && i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败");
        }
    }

    public static Connection getDate() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, pass);
        } catch (Exception e) {

        }
        return connection;
    }

    public static void close(AutoCloseable ac) {
        try {
            if (ac != null) {
                ac.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
